

import pygame
import random

ScreenSize = [480, 700]
FIRE_ID = 30
class BaseSprite(pygame.sprite.Sprite):
    def __init__(self, filename, speed=1):
        super().__init__()
        self.image = pygame.image.load(filename)
        self.rect = self.image.get_rect()
        self.speed = speed

    def update(self, *args):
        self.rect.y += self.speed


class BackGroundSprite(BaseSprite):
    """背景图精灵类"""
    def __init__(self,is_pre=False, speed=1):
        super().__init__('./images/background.png', speed)
        # 判断是否是预备图片
        if is_pre:
            self.rect.y = -self.rect.h


    def update(self):
        """更新"""
        super().update()
        if self.rect.y >= ScreenSize[1]:
            self.rect.y = -self.rect.h


class PlaneSprite(BaseSprite):
    """我方飞机精灵类"""
    def __init__(self,speed=1):
        super().__init__('./images/me1.png', speed)
        self.rect.centerx = 240
        self.rect.centery = 630

    def move(self, num):
        self.rect.x+=num
        if self.rect.x<0:
            self.rect.x = 10
        elif self.rect.x>ScreenSize[0]-self.rect.w:
            self.rect.x = ScreenSize[0]-self.rect.w-10


class EnemySprite(BaseSprite):
    """敌方飞机精灵类"""
    def __init__(self,speed=1):
        super().__init__('./images/enemy1.png', speed)
        self.rect.x =random.randint(10, 480-self.rect.w-10)
        self.rect.y = 0

    def update(self):
        """更新"""
        super().update()
        if self.rect.y > 700:
            self.kill()


class BulletSprite(BaseSprite):
    """子弹类"""
    def __init__(self,x,y, speed=1):
        super().__init__('./images/bullet1.png', speed)
        self.rect.centerx = x
        self.rect.y = y

    def update(self, *args):
        self.rect.y-=self.speed
        if self.rect.y< 0:
            self.kill()


class PlaneGame():
    """飞机大战游戏"""
    def __init__(self):
        # 初始化
        pygame.init()
        # 设置屏幕尺寸
        self.screen = pygame.display.set_mode(ScreenSize)
        # 设置飞机大战标题
        pygame.display.set_caption("飞机大战")
        self.is_loop = True
        self.is_running = True
        # 是时钟
        self.clock = pygame.time.Clock()
        # 创建精灵类
        self.__create_sprite()
        pygame.time.set_timer(pygame.USEREVENT, 2000)
        # 定时发射子弹
        pygame.time.set_timer(FIRE_ID, 800)
        self.go_image = pygame.image.load("./images/gameover.png")
        self.go_image_rect = self.go_image.get_rect()


    def start(self):
        """启动游戏"""
        while self.is_loop:
            self.__event_handler()
            self.screen.fill([0,0,0])
            if self.is_running:
                self.__update_sprite()
            else:
                self.screen.blit(self.go_image, self.go_image_rect)
            # 现在每s最多60帧
            self.clock.tick(60)
            pygame.display.update()
        pygame.quit()

    def __event_handler(self):
        """事件处理"""
        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                self.is_loop = False
            if e.type == pygame.KEYDOWN:
                if e.key == pygame.K_LEFT:
                    self.hero.move(-10)
                elif e.key == pygame.K_RIGHT:
                    self.hero.move(+10)
            elif e.type == pygame.USEREVENT:
                for i in range(4):
                    es = EnemySprite()
                    self.es_group.add(es)
            elif e.type == FIRE_ID:
                for i in range(3):
                    bullet = BulletSprite(self.hero.rect.centerx, self.hero.rect.y-i*20)
                    self.bullet_group.add(bullet)


    def __create_sprite(self):
        # 创建对象
        bg = BackGroundSprite()
        bg1 = BackGroundSprite(True)
        # 将精灵对象添加到精灵组当中
        self.bg_group = pygame.sprite.Group(bg, bg1)
        self.hero = PlaneSprite()
        self.hero_group = pygame.sprite.Group(self.hero)
        self.es_group =pygame.sprite.Group()
        self.bullet_group = pygame.sprite.Group()


    def __update_sprite(self):
        """更新精灵"""
        # 精灵组更新
        self.bg_group.update()
        self.es_group.update()
        self.bullet_group.update()
        #精灵组渲染
        self.bg_group.draw(self.screen)
        self.hero_group.draw(self.screen)
        self.es_group.draw(self.screen)
        self.bullet_group.draw(self.screen)
        # 检测子弹和敌方飞机的碰撞，如果发生碰撞则消失
        pygame.sprite.groupcollide(self.bullet_group, self.es_group, True, True)
        # 检测我方飞机是否与敌方飞机发生碰撞，如果是则游戏结束
        s_lst = pygame.sprite.spritecollide(self.hero, self.es_group, False)
        if s_lst:
            self.delete_sprites()
            self.is_running = False

    def delete_sprites(self):
        """删除所有精灵组"""
        pass
        # self.es_group.remove()
        # self.bullet_group.remove()

if __name__ == '__main__':
    plane = PlaneGame()
    plane.start()